<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts/core';
import { PieChart, GaugeChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { getTrainingIntensity } from '../../api/activity';

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  GaugeChart,
  CanvasRenderer
]);

const props = defineProps({
  userId: {
    type: String,
    required: true
  },
  dateRange: {
    type: Object,
    default: () => ({})
  },
  chartType: {
    type: String,
    default: 'pie' // pie 或 gauge
  }
});

const loading = ref(true);
const chartRef = ref(null);
const chartInstance = ref(null);
const intensityData = ref({});
const chartId = `intensity-chart-${Date.now()}-${Math.floor(Math.random() * 1000)}`; // 生成唯一ID

// 获取数据并初始化图表
const initChart = async () => {
  loading.value = true;
  try {
    const params = {
      startDate: props.dateRange.startDate,
      endDate: props.dateRange.endDate
    };
    
    intensityData.value = await getTrainingIntensity(props.userId, params);
    renderChart();
  } catch (error) {
    console.error('获取数据失败', error);
  } finally {
    loading.value = false;
  }
};

// 渲染图表
const renderChart = () => {
  if (!chartRef.value) return;
  
  // 销毁旧实例
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  
  // 创建新实例
  chartInstance.value = echarts.init(chartRef.value);
  
  // 处理数据
  const zones = Object.keys(intensityData.value);
  const data = zones.map(zone => ({
    name: zone,
    value: intensityData.value[zone]
  })).filter(item => item.value > 0);
  
  // 颜色映射
  const colorMap = {
    '恢复区 (< 120)': '#91cc75',
    '有氧区 (120-140)': '#5470c6',
    '耐力区 (140-160)': '#fac858',
    '无氧区 (160-180)': '#ee6666',
    '极限区 (> 180)': '#73c0de'
  };
  
  let option = {};
  
  if (props.chartType === 'pie') {
    option = {
      title: {
        text: '心率区间分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} 次 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        top: 'center',
        data: zones
      },
      series: [
        {
          name: '训练强度',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data,
          color: data.map(item => colorMap[item.name])
        }
      ]
    };
  } else {
    // 计算总次数和百分比
    const total = data.reduce((sum, item) => sum + item.value, 0);
    const gaugeData = data.map(item => ({
      name: item.name,
      value: (item.value / total * 100).toFixed(1),
      title: {
        offsetCenter: ['0%', '-30%']
      },
      detail: {
        valueAnimation: true,
        offsetCenter: ['0%', '0%']
      }
    }));
    
    option = {
      title: {
        text: '心率区间比例',
        left: 'center'
      },
      tooltip: {
        formatter: '{b}: {c}%'
      },
      series: [
        {
          type: 'gauge',
          startAngle: 90,
          endAngle: -270,
          pointer: {
            show: false
          },
          progress: {
            show: true,
            overlap: false,
            roundCap: true,
            clip: false,
            itemStyle: {
              color: function(params) {
                return colorMap[data[params.dataIndex].name];
              }
            }
          },
          axisLine: {
            lineStyle: {
              width: 40
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: false
          },
          data: gaugeData,
          title: {
            fontSize: 12
          },
          detail: {
            width: 50,
            height: 14,
            fontSize: 14,
            color: 'auto',
            formatter: '{value}%'
          }
        }
      ]
    };
  }
  
  // 设置图表配置
  chartInstance.value.setOption(option);
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chartInstance.value && chartInstance.value.resize();
  });
};

// 清理图表实例，防止内存泄漏
const disposeChart = () => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
    chartInstance.value = null;
  }
};

// 监听属性变化时重新渲染图表
watch(() => props.chartType, () => {
  renderChart();
});

watch(() => props.dateRange, () => {
  initChart();
}, { deep: true });

watch(() => props.userId, () => {
  initChart();
});

// 组件挂载时初始化图表
onMounted(() => {
  initChart();
});

// 组件销毁时清理图表实例
onUnmounted(() => {
  disposeChart();
});
</script>

<template>
  <div class="chart-container">
    <div v-if="loading" class="loading">加载中...</div>
    <div :id="chartId" ref="chartRef" class="chart" v-else></div>
  </div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
  position: relative;
}
.chart {
  width: 100%;
  height: 100%;
}
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  min-height: 300px;
  color: #999;
  font-size: 14px;
}
</style> 